from flask import Blueprint, request

from py.Services.BookService import BookService
from py.commonResponse.CommonResponse import *
from py.commonResponse.Dict import Dict
from py.Services.SummaryService import SummaryService
from py.Services.LendService import LendService

bp_book = Blueprint('book', __name__, url_prefix="/books")  # 蓝图使用方法，参数里给定文件名，还可以给定url前缀


# 查找所有图书
@bp_book.route('', methods=['GET'])
def book_Query_All():
    bookList = BookService.Book_Query_All()
    bookList1 = []
    for book in bookList:
        bookList1.append(dict(book))
    if not bookList1:
        return createForSuccessWM("系统里一本书都没有~(￣▽￣)~*")
    return createForSuccessWMD('查找成功', bookList1)


# 通过书名的模糊查找
@bp_book.route('/name/<string:name>', methods=['GET'])
def book_Query_ByName(name):
    bookList = BookService.Book_Query_ByName(name)
    bookList1 = []
    for book in bookList:
        bookList1.append(dict(book))
    if not bookList1:
        return createForSuccessWM("通过此名字找不到")
    return createForSuccessWMD('查找成功', bookList1)


# 通过category的模糊查找
@bp_book.route('/category/<string:category>', methods=['GET'])
def book_Query_ByCategory(category):
    bookList = BookService.Book_Query_ByCategory(category)
    bookList1 = []
    for book in bookList:
        bookList1.append(dict(book))
    if not bookList1:
        return createForSuccessWM("通过此category找不到")
    return createForSuccessWMD('查找成功', bookList1)


# 通过ISBON的精准查找
@bp_book.route('/ISBN/<string:ISBN>', methods=['GET'])
def book_Query_ByISBN(ISBN):
    book = BookService.Book_Query_ByISBN(ISBN)
    if book == "通过ISBN没查到这本书":
        return createForSuccessWM(book)
    return createForSuccessWMD('查找成功', dict(book))


#  新增书籍
@bp_book.route('', methods=['POST'])
def book_Insert():
    book = request.json
    msg = BookService.Book_Insert(Dict(book))
    return createForSuccessWM(msg)


#  删除书籍
@bp_book.route('', methods=['DELETE'])
def book_Delete():
    book = request.json
    Book = Dict(book)
    recordList = SummaryService.Record_Query_ByISBN(Book.ISBN)
    for record in recordList:
        LendService.ReturnBook(record,x=0)
    SummaryService.Record_Delete_ByISBN(Book.ISBN)
    msg = BookService.Book_Delete(Dict(book))
    return createForSuccessWM(msg)


#  修改书籍
@bp_book.route('', methods=['PUT'])
def book_Update():
    book = request.json
    msg = BookService.Book_Update(Dict(book))
    return createForSuccessWM(msg)

# 展示点击量最多书籍
@bp_book.route('hot', methods=['GET'])
def getHotBook():
    bookList = SummaryService.Book_LentMost()
    bookList1 = []
    for book in bookList:
        bookList1.append(dict(book))
    if not bookList1:
        return createForSuccessWM("最火书籍为空")
    return createForSuccessWMD('查找成功', bookList1)